import Vue from "vue";
import VueRouter from "vue-router";
import routes from './router'
import service from '../service/services'
import pageRouters from '../pages/index'


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter);



const router = new VueRouter({
    routes
});
router.addRoutes([...pageRouters])


router.beforeEach((to, from, next) => {

    const role = localStorage.getItem('isLogin');
    if (!role && to.path !== '/') {
        next('/');
    } else {
        next();
    }
    // let isLogin = localStorage.getItem('isLogin');

    // if (to.name == 'Login') {
    //     next()
    // } else {
    //     if (isLogin) {
    //         var currentJsonUser = localStorage.getItem("currentUser");
    //         var currentUser = JSON.parse(currentJsonUser);
    //         next()
    //         var userName = currentUser && currentUser.username;
    //         // if (!getRouter) {
    //         //     if (!getObjArr('router')) {
    //         //         service.user.getmenu(userName).then(res => {
    //         //             console.log(res)
    //         //             getRouter = res.data //后台拿到路由
    //         //             saveObjArr('router', getRouter) //存储路由到localStorage

    //         //             routerGo(to, next) //执行路由跳转方法
    //         //         })
    //         //     } else { //从localStorage拿到了路由
    //         //         getRouter = getObjArr('router') //拿到路由
    //         //         routerGo(to, next)
    //         //     }
    //         // }
    //     } else {
    //         next('/login')
    //     }


    // }

})
// var rotearray = []
// function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
//     const accessedRouters = asyncRouterMap;
//     console.log(asyncRouterMap)

//     for (let i = 0; i < asyncRouterMap.children.length; i++) {
//         const element = array[i];
//         var routeObj = {}
//         routeObj.path = element.href;
//         routeObj.name = element.label;
//         routeObj.meta = {
//             title: element.label
//         }
//         if (element.children && element.children.length != 0) {
//             filterAsyncRouter(element.children)
//         }
//     }

//     return accessedRouters
// }
// function routerGo(to, next) {
//     getRouter = filterAsyncRouter(getRouter) //过滤路由
//     router.addRoutes(getRouter) //动态添加路由
//     global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
//     next({ ...to, replace: true })
// }
// function saveObjArr(name, data) { //localStorage 存储数组对象的方法
//     localStorage.setItem(name, data)
// }

// function getObjArr(name) { //localStorage 获取数组对象的方法
//     return localStorage.getItem(name);

// }

export default router;